import { Component, OnInit } from '@angular/core';
import { PowerLoss } from "../../../entity/power-loss.model";
import { ActualWindPowerService } from "../../../service/actual-wind-power.service";
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { Device } from "../../../entity/device.model";
@Component({
	selector: 'app-power-assess',
	templateUrl: './power-assess.component.html',
	styleUrls: ['./power-assess.component.css']
})
export class PowerAssessComponent implements OnInit {
	//public farmCategory: FarmCategoryEnum = FarmCategoryEnum.winfarm;
	public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
	/**
	 * 当前选中下标
	 * 
	 * @type {number}@memberof PowerCompareComponent
	 */
	active: number = 0;

	/**
	 * 当前时间类型
	 * 
	 * @type {number}@memberof PowerCompareComponent
	 */
	dateType: number;

	/**
	* 当前风场风机
	* 
	* @type {TurbData}@memberof TurbineDetailComponent
	*/
	public currentDevice: Device;

	/**
	* 是否显示风机选择组件、选中风机类型定义
	* 
	* @type {boolean}@memberof TurbineDetailComponent
	*/
	public showSelector: boolean = false;
	private turbineId: number[];

	//时间选择
	public years: string[] = ["2020", "2019", "2018", "2017", "2016", "2015", "2014", "2013", "2012", "2011", "2010"]
	public currentYear: string = new Date().getFullYear().toString();
	public months: string[] = ["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"];
	public currentMonth: string = (new Date().getMonth() + 1).toString();

	//风机年度电量损耗数据集
	private powerLossData: PowerLoss[] = [];
	private originalPowerLoss: PowerLoss[] = [];

	//损失电量表格统计(年度)
	public actualPowerTotal: number;
	public limitLossTotal: number;
	public performLossTotal: number;
	public stopLossTotal: number;
	public badLossTotal: number;
	public usePercentTotal: number;

	//风机年度月份发电能力评估
	public monthsPowerCapacity: PowerLoss[] = [];
	public monthsPowerCapacityDad: PowerLoss[] = [];

	//风机年度损耗较大因素，月度损失电量月份、因素(较差月份)，年度发电能力（好、中、差）
	public powerLossReason: string;
	public powerLossReasonMonth: PowerLossReason[] = [];
	public powerJudge: string;

	//风机月度损耗数据集
	private originalPowerLossMonth: PowerLoss[] = [];
	private powerLossMonthData: PowerLoss[] = [];

	//风机月份每日发电能力评估
	public daysPowerCapacity: PowerLoss[] = [];
	public daysPowerCapacityDad: PowerLoss[] = [];

	//损失电量表格统计(月度)
	public monthActualPowerTotal: number;
	public monthLimitLossTotal: number;
	public monthPerformLossTotal: number;
	public monthStopLossTotal: number;
	public monthBadLossTotal: number;
	public monthUsePercentTotal: number;

	//月发电能力（好、中、差）,风机月度损耗较大因素，月度损失电量日期、因素(较差日期)，
	public powerJudgeMonth: string;
	public powerLossReasonDate: string;
	public powerLossReasonDay: PowerLossReason[] = [];

	/**
	 * echart series(饼图)
	* 
	* @type {any[]}@memberof TurbineTrendComponent
	*/
	public yearPieSeries = [];
	public monthPieSeries = [];

	/**
	 * echart series(柱图)
	* 
	* @type {any[]}@memberof TurbineTrendComponent
	*/
	yearColumnSeries = [];
	monthColumnSeries = [];

	//风机月份柱图X轴
	public xAxisData: string[] = [];
	public xAxisDataMonth: string[] = [];


	/**
	* 滑入风机系统tab时显示对应的风机系统
	* 
	* @type {}@memberof TurbineDetailComponent
	*/
	public onMouseEnter() {
		this.showSelector = true;
	}
	/**
	* 滑出风机系统tab时隐藏对应的风机系统
	* 
	* @type {}@memberof TurbineDetailComponent
	*/
	public onMouseLeave(ev) {
		if (!ev.toElement) return false;
		this.showSelector = false;
	}

	onSelectFarmRadio(ev: Device[]) {
		this.turbineId = [];
		this.currentDevice = ev[0];
		this.turbineId.push(ev[0].deviceId);
		this.showSelector = false;
		this.onSearch(this.active);
	}

	constructor(
		private actualWindPowerService: ActualWindPowerService,
	) { }

	ngOnInit() {

	}

	public onChangeYear(year: string) {
		this.currentYear = year;
	}
	public onChangeMonth(month: string) {
		this.currentMonth = month;
	}
	public onClickHeader(n: number) {
		this.active = n;
		this.onSearch(this.active)
	}

	public onSearch(active: number) {
		this.initEchartsData(active);
	}

	initEchartsData(active: number) {
		if (active == 0) {
			let time = this.currentYear;
			this.dateType = 3;

			this.actualWindPowerService.getPowerLossDataByturbineId(this.turbineId, this.dateType, time)
				.then(res => {
					if (!res) { return false; };
					this.powerLossData = [];
					this.originalPowerLoss = [];
					this.monthsPowerCapacity = [];
					this.monthsPowerCapacityDad = [];
					this.powerLossReasonMonth = [];

					//风机损失电量数据
					this.originalPowerLoss = [...res];
					this.powerLossData.push(...this.originalPowerLoss);

					//风机每月电量损失柱状图data
					let actualPowerArr: number[] = [];
					let limitLossArr: number[] = [];
					let performLossArr: number[] = [];
					let stopLossArr: number[] = [];
					let badLossArr: number[] = [];
					let usePercentArr: number[] = [];

					//损失总量表格数据统计
					this.actualPowerTotal = 0;
					this.limitLossTotal = 0;
					this.performLossTotal = 0;
					this.stopLossTotal = 0;
					this.badLossTotal = 0;

					let xAxisDataMonth = [];

					this.powerLossData.forEach((o, index) => {
						if (o != null) {
							this.actualPowerTotal += o.actualPower;
							this.limitLossTotal += o.limitLoss;
							this.performLossTotal += o.performLoss;
							this.stopLossTotal += o.stopLoss;
							this.badLossTotal += o.badLoss;

							actualPowerArr[index] = (o.actualPower)
							limitLossArr[index] = (o.limitLoss)
							performLossArr[index] = (o.performLoss)
							stopLossArr[index] = (o.stopLoss)
							badLossArr[index] = (o.badLoss)
							usePercentArr[index] = (o.usePercent)

							if (o.usePercent >= 90) {
								this.monthsPowerCapacity.push(o)
							}
							if (o.usePercent < 60) {
								this.monthsPowerCapacityDad.push(o);
							}
						}
					})

					//影响风机年度发电能力的损耗原因
					let powerLossJudjeArr = []
					powerLossJudjeArr.push(
						{ name: "停机损失", value: this.stopLossTotal },
						{ name: "限电损失", value: this.limitLossTotal },
						{ name: "性能损失", value: this.performLossTotal },
						{ name: "坏点损失", value: this.badLossTotal },
					)
					let maxLoss = this.powerLossJudje(this.limitLossTotal, this.performLossTotal, this.stopLossTotal, this.badLossTotal);
					if (maxLoss > 0) {
						powerLossJudjeArr.forEach(o => {
							if (o.value == maxLoss) {
								this.powerLossReason = o.name;
							}
						})
					}

					//影响风机月度发电能力损耗原因
					this.monthsPowerCapacityDad.forEach(o => {
						if (o != null) {
							let powerLossJudjeturb = [];
							powerLossJudjeturb.push(
								{ name: "停机损失", value: o.stopLoss },
								{ name: "限电损失", value: o.limitLoss },
								{ name: "性能损失", value: o.performLoss },
								{ name: "坏点损失", value: o.badLoss },
							)
							let maxLossturb = this.powerLossJudje(o.stopLoss, o.limitLoss, o.performLoss, o.badLoss);
							powerLossJudjeturb.forEach(k => {
								if (k.value == maxLossturb) {
									let tuebPowerLossReason = {
										name: o.date,
										lossReason: k.name
									}
									this.powerLossReasonMonth.push(tuebPowerLossReason)
								}
							})
						}
					})

					//表格能量利用率统计
					this.usePercentTotal = ((this.actualPowerTotal) / (this.actualPowerTotal + this.limitLossTotal + this.performLossTotal + this.stopLossTotal + this.badLossTotal)) * 100;
					this.usePercentTotal = this.usePercentTotal ? this.usePercentTotal : 0;

					//发电能力评估
					if (this.usePercentTotal > 0) {
						if (this.usePercentTotal >= 90) {
							this.powerJudge = "好"
						}
						if (this.usePercentTotal < 80) {
							this.powerJudge = "差"
						}
					}

					//风场柱状图数据对象
					let columnSeries = {
						actualPower: actualPowerArr,
						limitLoss: limitLossArr,
						performLoss: performLossArr,
						stopLoss: stopLossArr,
						badLoss: badLossArr,
						usePercent: usePercentArr
					}

					this.xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
					this.yearColumnSeries = [
						{
							name: '实发电量',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeries.actualPower //[232.06, 163.09, 242.91, 302.84, 389.45, 287.05, 261.41, 199.73, 145.57, 195.77]
						},
						{
							name: '性能损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeries.performLoss //[5.28, 3.96, 8.24, 15.26, 10.60, 14.07, 16.23, 18.11, 7.13, -3.20]
						},
						{
							name: '停机损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeries.stopLoss //[24.84, 31.21, 13.21, 5.72, 3.93, 5.65, 6.70, 12.74, 11.10, 7.40]
						},
						{
							name: '限电损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeries.limitLoss //[1.65, 10.54, 15.19, 1.31, 0, 0, 0, 0, 0, 0]
						},
						{
							name: '坏点损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeries.badLoss //[1.65, 10.54, 15.19, 1.31, 0, 0, 0, 0, 0, 0]
						},
						{
							name: '能量利用率',
							type: 'line',
							yAxisIndex: 1,
							data: columnSeries.usePercent //[87.9599, 78.1057, 86.8927, 93.142, 96.403, 93.5712, 91.9388, 86.6201, 88.8768, 97.8957] 
						},
					]

					this.yearPieSeries = [
						{
							type: 'pie',
							radius: '45%',
							center: ['50%', '50%'],
							data: [
								{ value: this.actualPowerTotal, name: '实发电量' },
								{ value: this.performLossTotal, name: '性能损失' },
								{ value: this.stopLossTotal, name: '停机损失' },
								{ value: this.limitLossTotal, name: '限电损失' },
								{ value: this.badLossTotal, name: '坏点损失' }
							],
							label: {
								normal: {
									formatter: "{b}({d}%)"
								}
							},
							labelLine: {
								normal: {
									length: 6,
									length2: 6
								}
							},
							color: ['#22b14c', '#a349a4', '#ff7f27', '#00a2e8', '#FF0000'],
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]
				})
				.catch(error => {
					console.log("app-farm-power-assess", error);
				});

		} else {
			let time = new Date(this.currentYear + '-' + this.currentMonth);
			this.dateType = 2;

			this.actualWindPowerService.getMonthPowerLossDataByturbineId(this.turbineId, this.dateType, time)   //this.turbineId, this.dateType, startTime, endTime
				.then(res => {
					if (!res) { return false; };
					this.originalPowerLossMonth = [];
					this.powerLossMonthData = [];
					this.daysPowerCapacity = [];
					this.daysPowerCapacityDad = [];
					this.powerLossReasonDay = [];

					this.originalPowerLossMonth = [...res];
					this.powerLossMonthData = [...this.originalPowerLossMonth];

					//风场当月每日电量损失柱状图data
					let actualPowerArr: number[] = [];
					let limitLossArr: number[] = [];
					let performLossArr: number[] = [];
					let stopLossArr: number[] = [];
					let badLossArr: number[] = [];
					let usePercentArr: number[] = [];

					//损失总量表格数据统计
					this.monthActualPowerTotal = 0;
					this.monthLimitLossTotal = 0;
					this.monthPerformLossTotal = 0;
					this.monthBadLossTotal = 0;
					this.monthStopLossTotal = 0;

					//let powerLossTotal: PowerLossTotal;

					let xAxisDataMonth = [];
					this.powerLossMonthData.forEach(o => {
						if (o != null) {
							this.monthActualPowerTotal += o.actualPower;
							this.monthLimitLossTotal += o.limitLoss;
							this.monthPerformLossTotal += o.performLoss;
							this.monthBadLossTotal += o.badLoss;
							this.monthStopLossTotal += o.stopLoss;

							actualPowerArr.push(o.actualPower)
							limitLossArr.push(o.limitLoss)
							performLossArr.push(o.performLoss)
							stopLossArr.push(o.stopLoss)
							badLossArr.push(o.badLoss)
							usePercentArr.push(o.usePercent)

							xAxisDataMonth.push(o.date.substr(o.date.length - 2))

							if (o.usePercent >= 90) {
								this.daysPowerCapacity.push(o)
							}
							if (o.usePercent < 60) {
								this.daysPowerCapacityDad.push(o)
							}
						}
					})

					//影响风场月度发电能力的损耗原因
					let powerLossJudjeArr = []
					powerLossJudjeArr.push(
						{ name: "停机损失", value: this.monthStopLossTotal },
						{ name: "限电损失", value: this.monthLimitLossTotal },
						{ name: "性能损失", value: this.monthPerformLossTotal },
						{ name: "坏点损失", value: this.monthBadLossTotal },
					)
					let maxLoss = this.powerLossJudje(this.monthStopLossTotal, this.monthPerformLossTotal, this.monthLimitLossTotal, this.monthBadLossTotal);
					powerLossJudjeArr.forEach(o => {
						if (o.value == maxLoss) {
							this.powerLossReasonDate = o.name;
						}
					})

					//表格能量利用率统计
					this.monthUsePercentTotal = ((this.monthActualPowerTotal) / (this.monthActualPowerTotal + this.monthLimitLossTotal + this.monthPerformLossTotal + this.monthStopLossTotal + this.monthBadLossTotal)) * 100;
					this.monthUsePercentTotal = this.monthUsePercentTotal ? this.monthUsePercentTotal : 0;

					//发电能力评估
					if (this.monthUsePercentTotal > 0) {
						if (this.monthUsePercentTotal >= 90) {
							this.powerJudgeMonth = "好"
						}
						if (this.monthUsePercentTotal < 80) {
							this.powerJudgeMonth = "差"
						}
					}

					//影响风机月度发电能力损耗原因
					this.daysPowerCapacityDad.forEach(o => {
						let powerLossJudjeturb = [];
						powerLossJudjeturb.push(
							{ name: "停机损失", value: o.stopLoss },
							{ name: "限电损失", value: o.limitLoss },
							{ name: "性能损失", value: o.performLoss },
							{ name: "坏点损失", value: o.badLoss },
						)
						let maxLossDay = this.powerLossJudje(o.stopLoss, o.limitLoss, o.performLoss, o.badLoss);
						powerLossJudjeturb.forEach(k => {
							if (k.value == maxLossDay) {
								let turbPowerLossReason = {
									name: o.date,
									lossReason: k.name
								}
								this.powerLossReasonDay.push(turbPowerLossReason)
							}
						})
					})

					//风场月度柱状图数据对象、X轴
					this.xAxisDataMonth = xAxisDataMonth
					let columnSeriesMonth = {
						actualPower: actualPowerArr,
						limitLoss: limitLossArr,
						performLoss: performLossArr,
						stopLoss: stopLossArr,
						badLoss: badLossArr,
						usePercent: usePercentArr
					}

					this.monthColumnSeries = [
						{
							name: '实发电量',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeriesMonth.actualPower//[232.06, 163.09, 242.91, 302.84, 389.45, 287.05, 261.41, 199.73, 145.57, 195.77]
						},
						{
							name: '性能损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeriesMonth.performLoss//[5.28, 3.96, 8.24, 15.26, 10.60, 14.07, 16.23, 18.11, 7.13, -3.20]
						},
						{
							name: '停机损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeriesMonth.stopLoss//[24.84, 31.21, 13.21, 5.72, 3.93, 5.65, 6.70, 12.74, 11.10, 7.40]
						},
						{
							name: '限电损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeriesMonth.limitLoss//[1.65, 10.54, 15.19, 1.31, 0, 0, 0, 0, 0, 0]
						},
						{
							name: '坏点损失',
							type: 'bar',
							stack: '总量',
							label: {
								normal: {
									position: 'insideRight'
								}
							},
							data: columnSeriesMonth.badLoss//[1.65, 10.54, 15.19, 1.31, 0, 0, 0, 0, 0, 0]
						},
						{
							name: '能量利用率',
							type: 'line',
							yAxisIndex: 1,
							data: columnSeriesMonth.usePercent //[87.9599, 78.1057, 86.8927, 93.142, 96.403, 93.5712, 91.9388, 86.6201, 88.8768, 97.8957] 
						},
					]

					this.monthPieSeries = [
						{
							type: 'pie',
							radius: '45%',
							center: ['50%', '50%'],
							data: [
								{ value: this.monthActualPowerTotal, name: '实发电量' },
								{ value: this.monthPerformLossTotal, name: '性能损失' },
								{ value: this.monthStopLossTotal, name: '停机损失' },
								{ value: this.monthLimitLossTotal, name: '限电损失' },
								{ value: this.monthBadLossTotal, name: '坏点损失' }
							],
							label: {
								normal: {
									formatter: "{b}({d}%)"
								}
							},
							labelLine: {
								normal: {
									length: 6,
									length2: 6
								}
							},
							color: ['#22b14c', '#a349a4', '#ff7f27', '#00a2e8', '#FF0000'],
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]

				})
				.catch(error => {
					console.log("app-farm-power-assess", error);
				});

		}
	}

	private powerLossJudje(a: number, b: number, c: number, d: number) {
		// var max =  c - (a - b > 0 ? a : b) > 0 ? c : a - b > 0 ? a : b;
		var max = Math.max(a, b, c, d);
		return max
	}

}

interface seriesDateArr {
	actualPower: any[];
	limitLoss: any[];
	performLoss: any[];
	StopLoss: any[];
	usePercent: any[];
}

interface PowerLossReason {
	name: string;
	lossReason: string;
}

interface PowerLossTotal {
	actualPowerTotal: number;
	limitLossTotal: number;
	performLossTotal: number;
	stopLossTotal: number;
}




// WEBPACK FOOTER //
// ./src/app/module/performance/power-assess/power-assess.component.ts